package com.xdxc.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xdxc.model.entity.User;
import com.xdxc.mapper.UserMapper;
import com.xdxc.service.UserService;
import com.xdxc.utils.EncryptionUtils;
import com.xdxc.utils.RandomIdGenerator;
import com.xdxc.vo.UserRegisterVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService {


    @Override
    public Boolean registerByEmail(UserRegisterVo userRegisterVo) {
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail,userRegisterVo.getEmail()));
        if (user != null || !userRegisterVo.getConfirmPassword().equals(userRegisterVo.getPassword())) {
            return false;
        }
        byte[] salt = EncryptionUtils.generateSalt();
        String hashedPassword = EncryptionUtils.pbkdf2Hash(userRegisterVo.getPassword().toCharArray(), salt);
        List<String> roles=new ArrayList<>();
        RandomIdGenerator randomIdGenerator=new RandomIdGenerator(1,5);
        Long UserId=randomIdGenerator.generateId();
        roles.add("USER");
        User user1=User.builder()
                .id(UserId)
                .userId(UserId)
                .email(userRegisterVo.getEmail())
                .password(hashedPassword)
                .roles(roles)
                .salt(java.util.Base64.getEncoder().encodeToString(salt))
                .build();
        return this.save(user1);
    }
}
